using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.Nodes
{
    [Serializable()]
    public class NodeDetail : Csla.BusinessBase<NodeDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _nodeid = Guid.NewGuid();
        private Guid _parentnodeid = Guid.NewGuid();
        private string _name = string.Empty;
        private SmartDate _createdate = new SmartDate(DateTime.Now);

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid nodeid
        {
            get
            {
                CanReadProperty("nodeid", true);
                return _nodeid;
            }
            set
            {
                CanWriteProperty("nodeid", true);
                if (!_nodeid.Equals(value))
                {
                    _nodeid = value;
                    PropertyHasChanged("nodeid");
                }
            }
        }

        public Guid parentnodeid
        {
            get
            {
                CanReadProperty("parentnodeid", true);
                return _parentnodeid;
            }
            set
            {
                CanWriteProperty("parentnodeid", true);
                if (!_parentnodeid.Equals(value))
                {
                    _parentnodeid = value;
                    PropertyHasChanged("parentnodeid");
                }
            }
        }

        public string name
        {
            get
            {
                CanReadProperty("name", true);
                return _name;
            }
            set
            {
                CanWriteProperty("name", true);
                if (value == null)
                    value = string.Empty;
                if (!_name.Equals(value))
                {
                    _name = value;
                    PropertyHasChanged("name");
                }
            }
        }

        public DateTime createdate
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Date;
            }
        }

        public string createdateString
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Text;
            }
            set
            {
                CanWriteProperty("createdate", true);
                if (value == null)
                    value = string.Empty;
                if (!_createdate.Equals(value))
                {
                    _createdate.Text = value;
                    PropertyHasChanged("createdate");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _nodeid;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // name
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "name");
            //
            // createdate
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "createdateString");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in NodeDetail
            //AuthorizationRules.AllowRead("nodeid", "NodeDetailReadGroup");
            //AuthorizationRules.AllowRead("parentnodeid", "NodeDetailReadGroup");
            //AuthorizationRules.AllowRead("name", "NodeDetailReadGroup");
            //AuthorizationRules.AllowRead("createdate", "NodeDetailReadGroup");

            //AuthorizationRules.AllowWrite("name", "NodeDetailWriteGroup");
            //AuthorizationRules.AllowWrite("createdate", "NodeDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in NodeDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("NodeDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in NodeDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("NodeDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in NodeDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("NodeDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in NodeDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("NodeDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private NodeDetail()
        { /* require use of factory method */
        }

        public static NodeDetail NewNodeDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a NodeDetail");
            return DataPortal.Create<NodeDetail>();
        }

        public static NodeDetail NewNodeDetail(Guid NodeID, Guid ParentNodeID)
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a NodeDetail");
            return DataPortal.Create<NodeDetail>(new Criteria(NodeID, ParentNodeID));
        }

        public static NodeDetail GetNodeDetail(Guid nodeid)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a NodeDetail");
            return DataPortal.Fetch<NodeDetail>(new Criteria(nodeid));
        }

        public static void DeleteNodeDetail(Guid nodeid)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a NodeDetail");
            DataPortal.Delete(new Criteria(nodeid));
        }

        public override NodeDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a NodeDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a NodeDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a NodeDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid nodeid;
            public Guid ParentNodeID;

            public Criteria(Guid nodeid)
            {
                this.nodeid = nodeid;
            }

            public Criteria(Guid nodeid, Guid ParentNodeID)
            {
                this.nodeid = nodeid;
                this.ParentNodeID = ParentNodeID;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@nodeid", criteria.nodeid);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetFolderByFolderID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _nodeid = dr.GetGuid("nodeid");
            _parentnodeid = dr.GetGuid("parentnodeid");
            _name = dr.GetString("name");
            //_createdate = dr.GetSmartDate("createdate", _createdate.EmptyIsMin);
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertFolder.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {

            DAL.AddParameter("@nodeid", _nodeid);

            if (_parentnodeid != Guid.Empty)
                DAL.AddParameter("@parentnodeid", _parentnodeid);
            else
                DAL.AddParameter("@parentnodeid", DBNull.Value);

            DAL.AddParameter("@name", _name);

            //DAL.AddParameter("@name", _name);
            //DAL.AddParameter("@nodeid", _nodeid);
            //cm.Parameters["@Newnodeid"].Direction = ParameterDirection.Output;
            //DAL.AddParameter("@parentnodeid", _parentnodeid);
            //cm.Parameters["@Newparentnodeid"].Direction = ParameterDirection.Output;
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateFolder.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@nodeid", _nodeid);

            if (_parentnodeid != Guid.Empty)
                DAL.AddParameter("@parentnodeid", _parentnodeid);
            else
                DAL.AddParameter("@parentnodeid", DBNull.Value);

            DAL.AddParameter("@name", _name);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_nodeid));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteFolder.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@nodeid", criteria.nodeid);
            DAL.AddParameter("@archived", 1);
        }

        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
